﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace Uranus.WeiStationAPI
{
    public class VisitAttribute : ActionFilterAttribute
    {
        private const string Key = "__action_duration__";

        /// <summary>
        /// 方法执行开始前
        /// </summary>
        /// <param name="actionContext"></param>
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            //检测是否停止方法执行，如果停止 则取传过来的数据作为返回值 此时不会执行OnActionExecuted 方法
            if (actionContext.Request.Properties.ContainsKey("RequestEnd_Response"))
            {
                actionContext.Response = actionContext.Request.Properties["RequestEnd_Response"] as System.Net.Http.HttpResponseMessage;
                Hanlder(actionContext.Request, actionContext.Response);
            }
        }
        /// <summary>
        /// 方法执行完成后
        /// </summary>
        /// <param name="actionExecutedContext"></param>
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            Hanlder(actionExecutedContext.Request, actionExecutedContext.Response);
        }


        public void Hanlder(System.Net.Http.HttpRequestMessage httpRequestMessage,
                            System.Net.Http.HttpResponseMessage httpResponseMessage)
        {
            Uranus.WeiStationAPI.Models.VisitDTO visitDTO = null;
            if (httpRequestMessage.Properties.ContainsKey("VisitDTO"))
            {
                visitDTO = httpRequestMessage.Properties["VisitDTO"] as Uranus.WeiStationAPI.Models.VisitDTO;
            }
            if (visitDTO != null && httpRequestMessage.Properties.ContainsKey(Key))
            {
                var stopWatch = httpRequestMessage.Properties[Key] as Stopwatch;
                if (stopWatch != null)
                {
                    stopWatch.Stop();
                    //var actionName = actionExecutedContext.ActionContext.ActionDescriptor.ActionName;
                    //var controllerName = actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
                    visitDTO.TimeSpan = stopWatch.Elapsed.TotalMilliseconds.ToString();
                }
            }

            if (httpRequestMessage.Method.Method == "POST")
            {
                if (httpResponseMessage != null) httpResponseMessage.Headers.Add("Access-Control-Allow-Origin", "*");
            }
            if (visitDTO != null && visitDTO.Url != null && visitDTO.Url.Contains("safety/VisitLog")) return;
            if (httpRequestMessage.Properties.ContainsKey("Parameter") && visitDTO != null)
            {
                Dictionary<string, object> dictionary =
                    httpRequestMessage.Properties["Parameter"] as Dictionary<string, object>;

                if (dictionary != null && dictionary.ContainsKey("UserID"))
                {
                    visitDTO.UserID = dictionary["UserID"].ToString();
                }
                if (dictionary != null && dictionary.ContainsKey("terminal"))
                {
                    visitDTO.Site = dictionary["terminal"].ToString();
                }
                if (dictionary != null)
                {
                    List<string> removekey = new List<string>() { "password", "u_id", "UserID", "terminal", "callback", "jsonp", "_d", "_e" };
                    foreach (KeyValuePair<string, object> keyValuePair in dictionary)
                    {
                        if (keyValuePair.Value != null && keyValuePair.Value.ToString() != "null" && !visitDTO.parms.ContainsKey(keyValuePair.Key) && !removekey.Contains(keyValuePair.Key))
                        {

                            visitDTO.parms.Add(keyValuePair.Key, keyValuePair.Value);
                        }
                    }

                }
            }
            
            DTCash.Logger.NodeLog.NodeLogQueueHandler.AddLog("Monitor", "访问", "", visitDTO);
        }
    }
}